<?php

/**
 * @author @author Samrat Khan & Sadik Sarfaraz - Apr 25, 2013
 */
// Set timezone
date_default_timezone_set("UTC");

// Time format is UNIX timestamp or
// PHP strtotime compatible strings

/**
 * 
 * @param string $time1 is the first input time given by client
 * @param string $time2 is the second input time after delivary
 * @param numeric $precision it is difference between two times used for genarating SLA
 * @return string implode
 */
function dateDiff($time1, $time2, $precision = 6) {
    // If not numeric then convert texts to unix timestamps
    if (!is_int($time1)) {
        $time1 = strtotime($time1);
    }
    if (!is_int($time2)) {
        $time2 = strtotime($time2);
    }

    // If time1 is bigger than time2
    // Then swap time1 and time2
    if ($time1 > $time2) {
        $ttime = $time1;
        $time1 = $time2;
        $time2 = $ttime;
    }

    // Set up intervals and diffs arrays
    $intervals = array('year', 'month', 'day', 'hour', 'minute', 'second');
    $diffs = array();

    // Loop thru all intervals
    foreach ($intervals as $interval) {
        // Set default diff to 0
        $diffs[$interval] = 0;
        // Create temp time from time1 and interval
        $ttime = strtotime("+1 " . $interval, $time1);
        // Loop until temp time is smaller than time2
        while ($time2 >= $ttime) {
            $time1 = $ttime;
            $diffs[$interval]++;
            // Create new temp time from time1 and interval
            $ttime = strtotime("+1 " . $interval, $time1);
        }
    }

    $count = 0;
    $times = array();
    // Loop thru all diffs
    foreach ($diffs as $interval => $value) {
        // Break if we have needed precission
        if ($count >= $precision) {
            break;
        }
        // Add value and interval 
        // if value is bigger than 0
        if ($value > 0) {
            // Add s if value is not 1
            if ($value != 1) {
                $interval .= "s";
            }
            // Add value and interval to times array
            //$times[] = $value . " " . $interval;
            $times[] = $value;
            $count++;
        }
    }

    // Return string with times
    return implode(":", $times);
    
}

function strToDateTime($date, $format) {
    if(!($date = strToDate($date, $format))) return;
    $dateTime = array('sec' => 0, 'min' => 0, 'hour' => 0, 'day' => 0, 'mon' => 0, 'year' => 0, 'timestamp' => 0);
    foreach($date as $key => $val) {
        switch($key) {
            case 'd':
            case 'j': $dateTime['day'] = intval($val); break;
            case 'D': $dateTime['day'] = intval(date('j', $val)); break;
           
            case 'm':
            case 'n': $dateTime['mon'] = intval($val); break;
            case 'M': $dateTime['mon'] = intval(date('n', $val)); break;
           
            case 'Y': $dateTime['year'] = intval($val); break;
            case 'y': $dateTime['year'] = intval($val)+2000; break;
           
            case 'G':
            case 'g':
            case 'H':
            case 'h': $dateTime['hour'] = intval($val); break;
           
            case 'i': $dateTime['min'] = intval($val); break;
           
            case 's': $dateTime['sec'] = intval($val); break;
        }
    }
    $dateTime['timestamp'] = mktime($dateTime['hour'], $dateTime['min'], $dateTime['sec'], $dateTime['mon'], $dateTime['day'], $dateTime['year']);
    return $dateTime;
}
function timerFormat($start_time, $end_time, $std_format = false) {
    $total_time = $end_time - $start_time;
    $days = floor($total_time / 86400);
    $hours = floor($total_time / 3600);
    $minutes = intval(($total_time / 60) % 60);
    $seconds = intval($total_time % 60);
    $results = "";
    if ($std_format == false) {
        if ($days > 0)
            $results .= $days . (($days > 1) ? " days " : " day ");
        if ($hours > 0)
            $results .= $hours . (($hours > 1) ? " hours " : " hour ");
        if ($minutes > 0)
            $results .= $minutes . (($minutes > 1) ? " minutes " : " minute ");
        if ($seconds > 0)
            $results .= $seconds . (($seconds > 1) ? " seconds " : " second ");
    }
    else {
        if ($days > 0)
            $results = $days . (($days > 1) ? " days " : " day ");
            $results = sprintf("%s%02d:%02d:%02d", $results, $hours, $minutes, $seconds);
    }
    return $results;
}

function secondstotime($seconds) {
  $t = round($seconds);
  return sprintf('%02d:%02d:%02d', ($t/3600),($t/60%60), $t%60);
}

function hourstosecods($hour) { // $hour must be a string type: "HH:mm:ss"
    $parse = array();
    if (!preg_match('#^(?<hours>[\d]{2}):(?<mins>[\d]{2}):(?<secs>[\d]{2})$#', $hour, $parse)) {
        // Throw error, exception, etc
        throw new RuntimeException("Hour Format not valid");
    }

    return (int) $parse['hours'] * 3600 + (int) $parse['mins'] * 60 + (int) $parse['secs'];
}
?>
